/**
 * @ClassName chapter1.KP4_selectsort
 * @Description: TODO
 * @Author: JCC
 * @CreateTime: 2023/10/7 14:24
 */

import java.util.Arrays;

/**
 * 插入排序
 */
public class KP5_insertsort {

    /**
     * 每次比较都交换，内层适用while循环
     * @param array
     */
    public static void insertSort(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        int N = array.length;
        for (int i = 1; i < N; i++) {
            int end = i;
            while (end - 1 >= 0 && array[end] < array[end - 1]) {
                swap(array, end - 1, end);
                end--;
            }
        }
    }

    /**
     * 每次比较都交换，内层适用for循环
     * @param array
     */
    public static void insertSort1(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        int N = array.length;
        for (int i = 1; i < N; i++) {
            for (int end = i; end - 1 >= 0 && array[end] < array[end - 1]; end--) {
                swap(array, end - 1, end);
            }
        }
    }

    /**
     * 比较完了再交换，内层适用for循环
     * @param array
     */
    public static void insertSort2(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        int N = array.length;
        for (int i = 1; i < N; i++) {
            int tmp = array[i];
            int j;
            for (j = i - 1; j >= 0 && array[j] > tmp; j--) {
                array[j + 1] = array[j];
            }
            array[j + 1] = tmp;
        }
    }

    /**
     * insertSort2代码简写
     * @param array
     */
    public static void insertSort3(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        int N = array.length;
        for (int i = 1,tmp,j; i < N; i++) {
            tmp = array[i];
            for (j = i - 1; j >= 0 && array[j] > tmp; j--) {
                array[j + 1] = array[j];
            }
            array[j + 1] = tmp;
        }
    }

    public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static void main(String[] args) {
        int[] array = new int[]{2, 4, 1, 5, 17, 1, 15, 86};
        System.out.println(Arrays.toString(array));
        //insertSort(array);
        //insertSort1(array);
        //insertSort2(array);
        insertSort3(array);
        System.out.println(Arrays.toString(array));
    }
}
